package chapter10_3;

import java.io.Reader;
import java.util.List;

import chapter10_3.dao.StudentMapper;
import chapter10_3.po.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

public class Chaper10_3_BatisTest {
    private static SqlSessionFactory sqlSessionFactory = null;
    // 初始化SqlSessionFactory对象
    static {
        try {
            // 使用MyBatis提供的Resources类加载MyBatis的配置文件
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            // 构建SqlSessionFactory工厂
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取SqlSession对象的静态方法
    public static SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }

    /**
     * 1.分页查询学生信息
     */

    public void findStudentListIfPageTest() {
        // 获取SqlSession
        SqlSession sqlSession = getSession();
        // SqlSession执行映射文件中定义的SQL，并返回映射结果
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        PageHelper.startPage(1, 3);
        List<Student> list = studentMapper.findStudentListIfPage();
        // 用PageInfo对分页结果进行包装
        PageInfo page = new PageInfo(list);
        // 输出PageInfo的属性
        System.out.println("当前页码：" + page.getPageNum());
        System.out.println("每页数据数：" + page.getPageSize());
        System.out.println("数据总数：" + page.getTotal());
        System.out.println("总页数：" + page.getPages());
        for (Student stu : (List<Student>)(page.getList())) {
            System.out.println(stu);
        }

        // 关闭SqlSession
        sqlSession.close();
    }

    public static void main(String[] args) {
        Chaper10_3_BatisTest test = new Chaper10_3_BatisTest();
        test.findStudentListIfPageTest();
    }

}
